import React, { useEffect, useState } from 'react';
import { Result, Button, Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { paypalPayment, paypalCancel } from '@/service';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';

const PaymentStatus = () => {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const { t } = useTranslation();
    const location = useLocation();
    const query = new URLSearchParams(location.search);
    const code = query.get('code');
    const orderId = query.get('token');
    const [intervalId, setIntervalId] = useState(null); // 保存 interval ID
    const fetchPaymentStatus = async (orderId) => {
        setLoading(true);
        try {
            const response = await paypalPayment(orderId);
            const currentState = response.data?.state ?? 2; // 如果未返回状态，则设置为失败状态 2
            setStatus(currentState);
        } catch (error) {
            setStatus(2); // 如果出错，设置为失败状态
        } finally {

            setLoading(false);
        }
    };
    const cancelStatus = async () => {
        try {
            let params = {
                orderId: orderId
            }
            const response = await paypalCancel(params);
        } catch (error) {
            console.error(error);
        }
    };

    useEffect(() => {
        if (query) {
            if (code == 1) {
                if (orderId) {
                    setStatus(0);
                    fetchPaymentStatus(orderId);
                    const id = setInterval(() => {
                        fetchPaymentStatus(orderId); // 每3秒调用一次
                    }, 3000);
                    setIntervalId(id);
                    return () => {
                        clearInterval(id);
                    };
                }
            } else if (code == 2) {
                setStatus(9);
                cancelStatus();
            }
        }
    }, []);

    useEffect(() => {
        // 如果状态不为 null和0时 停止轮询
        if (status !== null && status !== 0) {
            clearInterval(intervalId);
            setIntervalId(null);
        }
    }, [status]);

    // const handleRetry = () => {
    //     const orderId = sessionStorage.getItem("orderId");
    //     setStatus(null);
    //     fetchPaymentStatus(orderId);
    //     const id = setInterval(() => {
    //         fetchPaymentStatus(orderId);
    //     }, 30000);
    //     setIntervalId(id);
    // };
    const renderContent = () => {
        switch (status) {
            case 0: // 0
                return <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                    alignItems: 'center',
                    zIndex: 9999,
                    paddingTop: '100px'
                }}>
                    <span style={{ marginBottom: '20px', color: '#000000e0', fontSize: '24px' }}>{t('menu.rechargeResult.form.amount.Rules.loadingLabel')}</span>
                    <Spin indicator={<LoadingOutlined style={{ fontSize: 48 }} spin />} />
                </div>
            case 1:
                return (
                    <Result
                        status="success"
                        title={t('menu.rechargeResult.form.amount.Rules.successLabel')}
                        subTitle={t('menu.rechargeResult.form.amount.Rules.thankYouLabel')}
                        extra={[
                            <Button type="primary" key="home" onClick={() => window.location.href = '/'}>
                                {t('menu.rechargeResult.form.amount.Rules.returnHomeLabel')}
                            </Button>
                        ]}
                    />
                );
            case 2:
                return (
                    <Result
                        status="error"
                        title={t('menu.rechargeResult.form.amount.Rules.failureLabel')}
                        subTitle={t('menu.rechargeResult.form.amount.Rules.failureDetailLabel')}
                        extra={[
                            // <Button key="retry" onClick={handleRetry}>
                            //     重试支付
                            // </Button>,
                            <Button type="default" key="home" onClick={() => window.location.href = '/'}>
                                {t('menu.rechargeResult.form.amount.Rules.returnHomeLabel')}
                            </Button>
                        ]}
                    />
                );
            case 3:
                return (
                    <Result
                        status="warning"
                        title={t('menu.rechargeResult.form.amount.Rules.canceledLabel')}
                        subTitle={t('menu.rechargeResult.form.amount.Rules.paypalcanceledDetailLabel')}
                        extra={[
                            <Button type="default" key="home" onClick={() => window.location.href = '/'}>
                                {t('menu.rechargeResult.form.amount.Rules.returnHomeLabel')}
                            </Button>
                        ]}
                    />
                );
            case 4:
                return (
                    <Result
                        status="error"
                        title={t('menu.rechargeResult.form.amount.Rules.orderCreationFailedLabel')}
                        subTitle={t('menu.rechargeResult.form.amount.Rules.orderCreationFailedDetailLabel')}
                        extra={[
                            <Button type="default" key="home" onClick={() => window.location.href = '/'}>
                                {t('menu.rechargeResult.form.amount.Rules.returnHomeLabel')}
                            </Button>
                        ]}
                    />
                );
            case 9:
                return (
                    <Result
                        status="warning"
                        title={t('menu.rechargeResult.form.amount.Rules.canceledLabel')}
                        subTitle={t('menu.rechargeResult.form.amount.Rules.canceledDetailLabel')}
                        extra={[
                            <Button type="default" key="home" onClick={() => window.location.href = '/'}>
                                {t('menu.rechargeResult.form.amount.Rules.returnHomeLabel')}
                            </Button>
                        ]}
                    />
                );
            default:
                return null;
        }
    };

    return (
        <div>
            {renderContent()}
        </div>
    );
};

export default PaymentStatus;
